package com.example.mymvplibrary.presenter;

import com.example.mymvplibrary.model.BaseModel;
import com.example.mymvplibrary.view.BaseView;
import com.trello.rxlifecycle2.LifecycleProvider;

import java.lang.ref.WeakReference;

import java.lang.reflect.ParameterizedType;

import java.lang.reflect.Type;


public class BasePresenter<V extends BaseView,M extends BaseModel> implements RxPresenter<V>{
    //弱引用
    private WeakReference<V>mWeakReference;
    private   V mView;
    private M model;
    @Override
    public void bindView(V v) {
        mWeakReference=new WeakReference<V>(v);
            mView=mWeakReference.get();

//        if (mWeakReference!=null) {
//           mView=(V)Proxy.newProxyInstance(mWeakReference.get().getClass().getClassLoader(),
//                    mWeakReference.get().getClass().getInterfaces(), new InvocationHandler() {
//                        @Override
//                        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//                            if (mWeakReference==null||mWeakReference.get()==null){
//
//                            }
//                            return method.invoke(proxy,args);
//                        }
//                    });
//        }
        initMode();
    }
//利用反射动态创建
    private void initMode() {
        ParameterizedType genericInterfaces = (ParameterizedType) this.getClass().getGenericSuperclass();
        Type[] actualTypeArguments = genericInterfaces.getActualTypeArguments();
        Class<M> modelClass=(Class<M>)actualTypeArguments[1];
        try {
            model=modelClass.newInstance();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public V getmView() {
        return mView;
    }

    @Override
    public void destoryView() {
        if(mWeakReference!=null){
            mWeakReference.clear();
            mWeakReference=null;
        }
        if(mView!=null){
            mView=null;
        }
    }

    @Override
    public LifecycleProvider getLifecleProvider() {
        if(getmView()!=null){
            return (LifecycleProvider) getmView();
        }
        return null;
    }

    public M getModel() {
        return model;
    }
}
